<template>
  <div id="userCenter">
    <!--    标题卡片-->
    <a-card class="card_head" hoverable>
      <template #cover>
        <div class="person_background" style="position: relative">
          <a-space style="position: absolute; left: 30px; bottom: 30px">
            <a-avatar
              :src="COS_ENUM.COS_HOST + loginUserStore.loginUser.userAvatar + '?' + Date.now()"
              :size="100"
            />
            <div style="color: white; margin-left: 5px">
              <h3 class="user_name">{{ loginUserStore.loginUser.userName ?? '无名' }}</h3>
              <div class="desc">
                {{ loginUserStore.loginUser.userProfile ?? '这个人很懒，什么都没留下' }}
              </div>
            </div>
          </a-space>
          <a-button
            style="position: absolute; right: 30px; bottom: 35px"
            ghost
            size="middle"
            @click="showModal"
          >
            <SettingOutlined />
            个人设置
          </a-button>
        </div>
        <!--        <img alt="example" src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png" />-->
      </template>
      <!--      选项标签-->
      <a-menu
        style="font-size: 20px"
        v-model:selectedKeys="current"
        mode="horizontal"
        :items="items"
        @click="doMenuClick"
      />
    </a-card>

    <a-row style="max-width: 90%; margin: 0 auto; margin-top: 20px" justify="center" gutter="16">
      <a-col :span="17">
        <!--        主页-->
        <a-card v-if="knowSelected === 'home'" style="border: #eee solid" title="个人介绍">
          <div style="font-size: 18px">
            {{ loginUserStore.loginUser.userProfile ?? '这个人很懒，什么都没有写' }}
          </div>
        </a-card>
        <!--        个人中心-->
        <a-card v-if="knowSelected === 'my'" style="border: #eee solid" title="上传文件">

          <!--    搜索表单-->
          <a-form layout="inline" :model="searchParams" @finish="doSearch">
            <a-form-item label="文件名称">
              <a-input v-model:value="searchParams.name" placeholder="输入文件名称" allow-clear />
            </a-form-item>
            <a-form-item name="fillStatus" label="文件状态">
              <a-select
                v-model:value="searchParams.fillStatus"
                style="min-width: 180px"
                placeholder="请选择文件状态"
                :options="FILE_CREATE_STATUS_OPTIONS"
                allow-clear
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit">搜索</a-button>
            </a-form-item>
          </a-form>

          <FileListBig
            :dataList="dataList"
            :loading="loading1"
            :show-op="true"
            :can-edit="true"
            :can-delete="true"
            :on-reload="fetchData"
            :grid="{ gutter: 1, xs: 1, sm: 1, md: 2, lg: 2, xl: 3, xxl: 4 }"
            :show-status="true"
            :show-tag="false"
          />
          <a-pagination
            style="text-align: right"
            v-model:current="searchParams.current"
            v-model:pageSize="searchParams.pageSize"
            :total="total"
            @change="onPageChange"
          />
        </a-card>
<!--        模型页面-->
        <a-card v-if="knowSelected === 'model'"  style="border: #eee solid" title="我的模型">

          <!--    搜索表单-->
          <a-form layout="inline" :model="searchTrainParams" @finish="doTrainSearch">
            <a-form-item label="文件id">
              <a-input v-model:value="searchTrainParams.fileId" placeholder="输入文件Id" allow-clear />
            </a-form-item>
            <a-form-item label="模型">
              <a-input v-model:value="searchTrainParams.model" placeholder="输入模型名称名称" allow-clear />
            </a-form-item>
            <a-form-item name="trainStatus" label="模型状态">
              <a-select
                v-model:value="searchTrainParams.trainStatus"
                style="min-width: 180px"
                placeholder="请选择文件状态"
                :options="FILE_TRAIN_CREATE_STATUS_OPTIONS"
                allow-clear
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit">搜索</a-button>
            </a-form-item>
          </a-form>
          <div style="margin-bottom: 16px" />


          <a-table
            :columns="trainColumns"
            :data-source="dataTrainList"
            :pagination="trainPagination"
            @change="doTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'id'">
                <a :href="'/train/'+record.id">{{record.id }}</a>
              </template>
              <template v-if="column.dataIndex === 'fileId'">
                <a :href="'/file/'+record.fileId">{{record.fileId }}</a>
              </template>
              <template v-if="column.dataIndex === 'createTime'">
                {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
              <template v-if="column.dataIndex === 'trainStatus'">
                <a-tag :color="FILE_TRAIN_CREATE_STATUS_COLOR_ENUM[record.trainStatus]">{{
                    record.trainStatus
                  }}</a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a-popconfirm
                    v-if="dataList.length && record.userRole !== 'admin'"
                    title="确定删除嘛？"
                    @confirm="doDelete(record.id)"
                  >
                    <a-button danger>删除</a-button>
                  </a-popconfirm>
                </a-space>
              </template>
              </template>
          </a-table>
        </a-card>
      </a-col>
      <!--      用户信息-->
      <a-col :span="7">
        <a-card style="border: #eee solid">
          <a-descriptions :column="1">
            <a-descriptions-item label="用户编号">
              <div style="font-size: 20px; color: #aaa; width: 100%; text-align: right">
                {{ loginUserStore.loginUser.id }}
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="用户角色">
              <div style="font-size: 20px; color: #aaa; width: 100%; text-align: right">
                {{ loginUserStore.loginUser.userRole }}
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="注册时间">
              <div style="font-size: 20px; color: #aaa; width: 100%; text-align: right">
                {{ dayjs(loginUserStore.loginUser.createTime).format('YYYY-MM-DD') }}
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
    </a-row>
  </div>



  <a-modal
    v-model:open="openPersonalEditModal"
    title="个人信息编辑"
    @ok="handleOk"
    width="50%"
    :cancel-button-props="{ disable: true }"
  >
    <h3>头像设置：</h3>
    <div class="picture-upload" style="margin-left: 80px">
      <a-upload
        list-type="picture-card"
        :show-upload-list="false"
        :custom-request="handleUpload"
        :before-upload="beforeUpload"
      >
        <img
          v-if="loginUserStore.loginUser?.userAvatar"
          :src="COS_ENUM.COS_HOST + loginUserStore.loginUser.userAvatar + '?' + Date.now()"
          alt="avatar"
        />
        <div v-else>
          <loading-outlined v-if="loading"></loading-outlined>
          <plus-outlined v-else></plus-outlined>
        </div>
      </a-upload>
      <div class="ant-upload-text" style="color: #aaa; text-align: left">点击或拖拽上传图片</div>
    </div>
    <div style="margin-bottom: 16px" />
    <h3>修改用户信息：</h3>
    <div style="margin-left: 50px">
      <a-form :model="updateParams" style="margin-right: 10%" @finish="handleSubmit">
        <a-form-item field="id" label="用户id" style="min-width: 240px">
          <a-input v-model:value="updateParams.id" disabled />
        </a-form-item>
        <a-form-item field="userName" label="用户名" style="min-width: 240px">
          <a-input v-model:value="updateParams.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item field="userProfile" label="用户简介" style="min-width: 240px">
          <a-textarea
            v-model:value="updateParams.userProfile"
            default-value=""
            :auto-size="{
              minRows: 3,
              maxRows: 3,
            }"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100%">修改用户信息</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import COS_ENUM from '@/enums/CosEnum.ts'
import { SettingOutlined } from '@ant-design/icons-vue'
import { computed, onMounted, reactive, ref, toRaw } from 'vue'
import dayjs from 'dayjs'
import { message, type UploadProps } from 'ant-design-vue'
import { editUserUsingPost, updateUserAvatarUsingPost, userLogoutUsingGet } from '@/api/userController.ts'
import FileListBig from '@/components/FileListBig.vue'
import { listFileMyByPageUsingPost, listFileVoByPageUsingPost } from '@/api/fileController.ts'
import {
  FILE_CREATE_STATUS_OPTIONS,
  FILE_TRAIN_CREATE_STATUS_COLOR_ENUM,
  FILE_TRAIN_CREATE_STATUS_OPTIONS
} from '@/constant/file.ts'
import {
  deleteFileTrainUsingPost,
  listFileTrainByPageUsingPost,
  listFileTrainVoByPageUsingPost
} from '@/api/fileTrainController.ts'

const openPersonalEditModal = ref<boolean>(false)

const loading = ref<boolean>(true)

const updateParams = reactive<API.UserEditRequest>({
  id: 0,
  userName: '',
  userProfile: '',
})
const items = [
  {
    key: 'home',
    label: '主页',
    title: '主页',
  },
  {
    key: 'my',
    // icon: () => h(HomeOutlined),
    label: '上传文件',
    title: '上传文件',
  },
  {
    key: 'model',
    // icon: () => h(HomeOutlined),
    label: '创建模型',
    title: '创建模型',
  },
]

const loginUserStore = useLoginUserStore()

// 当前要高亮的菜单项
const current = ref<string[]>(['home'])

const knowSelected = ref<string>('home')
const doMenuClick = ({ key }) => {
  knowSelected.value = key
}

const showModal = () => {
  updateParams.id = loginUserStore.loginUser.id
  updateParams.userName = loginUserStore.loginUser.userName
  updateParams.userProfile = loginUserStore.loginUser.userProfile
  openPersonalEditModal.value = true
}

const handleOk = () => {
  openPersonalEditModal.value = false
}

const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 校验图片格式
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 jpg 或 png ')
  }
  // 校验图片大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('不能上传 2M 的图片')
  }
  return isJpgOrPng && isLt2M
}

/**
 * 上传图片
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true

  try {
    // 调用上传图片接口
    const res = await updateUserAvatarUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      // 重新请求一遍
      loginUserStore.fetchLoginUser()
    } else {
      message.error('图片上传失败' + res.data.message)
    }
  } catch (error) {
    console.error('图片上传失败', error)
    message.error('图片上传失败' + error.message)
  }

  loading.value = false
}

const handleSubmit = async () => {
  const res = await editUserUsingPost({
    ...updateParams,
  })
  // 操作成功
  if (res.data.code === 0 && res.data.data) {
    message.success('更新成功')
    loginUserStore.fetchLoginUser()
  } else {
    message.error('更新失败，' + res.data.message)
  }
}

const dataList = ref<API.FileVO[]>([])
const loading1 = ref(true)
const total = ref(0)
const searchParams = reactive<API.FileQueryRequest>({
  current: 1,
  pageSize: 8,
  sortField: 'createTime',
  sortOrder: 'descend',
}) // 局部更新
const fetchData = async () => {
  loading1.value = true
  // 转换搜索参数
  const params = {
    ...searchParams,
    tags: [] as string[],
  }
  const res = await listFileMyByPageUsingPost({
    ...params,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading1.value = false
}

const onPageChange = (page: number, pageSize: number) => {
  searchParams.current = page
  searchParams.pageSize = pageSize
  fetchData()
}

// 页面加载时获取数据, 请求一次
onMounted(() => {
  fetchData()
})

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// -------------- 训练参数

const trainColumns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '文件id',
    dataIndex: 'fileId'
  },
  {
    title: '训练模型',
    dataIndex: 'model',
  },
  {
    title: '训练简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '模型状态',
    dataIndex: 'trainStatus',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]


const dataTrainList = ref<API.FileTrainVO[]>([]) //整体更新
const trainTotal = ref(0)
// 搜索条件
const searchTrainParams = reactive<API.FileTrainQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
}) // 局部更新

// 分页参数 (computed 监听值的变化情况，改变则更新)
const trainPagination = computed(() => {
  return {
    current: searchTrainParams.current,
    pageSize: searchTrainParams.pageSize,
    total: trainTotal.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

const fetchTrainData = async () => {
  searchTrainParams.userId = loginUserStore.loginUser.id
  const res = await listFileTrainVoByPageUsingPost({
    ...searchTrainParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataTrainList.value = res.data.data.records ?? []
    trainTotal.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

//表格变化，然后重新获取数据
const doTableChange = (page: any) => {
  searchTrainParams.current = page.current
  searchTrainParams.pageSize = page.pageSize
  fetchData()
  fetchTrainData();
}
onMounted(() => {
  fetchTrainData();
})

// 删除数据
const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  const res = await deleteFileTrainUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchTrainData();
  } else {
    message.error('删除失败')
  }
}
// 搜索数据
const doTrainSearch = () => {
  // 重置页码
  searchTrainParams.current = 1
  fetchTrainData()
}

</script>

<style scoped>
#userCenter {
}
.card_head {
  max-width: 90%;
  margin: 0 auto;
  border: #eee solid;
}
.person_background a-space {
  position: absolute;
  bottom: 0;
  right: 0;
}

.person_background {
  width: 100%; /* 设置宽度 */
  height: 300px;
  background: url('../../assets/R-C.jpg') no-repeat center;
  background-size: cover; /* 让图片铺满整个元素 */
}

.user_name {
  font-size: 25px;
  margin-bottom: 0px;
}

.desc {
  text-align: left;
  color: white;
}

:deep(.ant-card-head-title) {
  font-size: 20px;
}
:deep(.ant-descriptions-item-label) {
  font-size: 20px;
}

.picture-upload :deep(.ant-upload) {
  margin: auto;
  width: 100% !important;
  height: 100% !important;
  min-width: 152px;
  min-height: 152px;
}

.picture-upload {
  max-width: 100%;
  max-height: 100%;
  text-align: left;
}

.picture-upload :deep(.ant-upload-wrapper) {
  overflow: hidden; /* 确保图像不会溢出 */
  position: relative;
  max-height: 40%;
  max-width: 40%;
}

.picture-upload img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图像的宽高比，并裁剪多余部分 */
  object-position: center; /* 将图像居中 */
}
</style>
